<?php
namespace App\Service;

use Illuminate\Support\Facades\DB;

class KehuService extends BaseService
{
    //客户

    public static function sel()
    {
        $res = self::dbConn(self::$dbKehu)
            ->select('area_id', 'area')
            ->groupBy('area_id')
            ->get();
        if (!count($res)) {
            return [];
        }
        $arys[] = ['id' => 0, 'title' => '所有'];
        foreach ($res as $v) {
            $areaOne = self::dbConn(self::$dbArea)->where('id', $v->area_id)->first();
            $pOne = self::dbConn(self::$dbArea)->where('id', $areaOne->pid)->first();
            $title = $pOne->title.'-'.$v->area;
            if ($pOne->pid) {
                $p2One = self::dbConn(self::$dbArea)->where('id', $pOne->pid)->first();
                $title = $p2One->title.'-'.$title;
            }
            $arys[] = [
                'id' => $v->area_id,
                'title' => $title,
            ];
        }
        return $arys;
    }

    /**
     * 列表
     * @param array $pages【start，limit】
     */
    public static function index($pas, $pages)
    {
        $start = ($pages['start'] - 1) * $pages['limit'];
        $db = self::dbConn(self::$dbKehu)->where('del', 0);
        if ($pas['area_id']) {
            $db = $db->where('area_id', $pas['area_id']);
        }
        $total = $db->count();
        $res = $db->skip($start)->take($pages['limit'])
            ->orderBy('id', 'desc')
            ->get();
        return self::toback(0, '', $res, $total);
    }

    /**
     * 详情
     * @param int $id
     */
    public static function one($id)
    {
        $res = self::dbConn(self::$dbKehu)->where('id', $id)->first();
        return self::toback(0, '', $res);
    }

    //导入
    public static function add($arys)
    {
        foreach ($arys as $ary) {
            $res = self::dbConn(self::$dbKehu)->where('cname', $ary['cname'])->first();
            if (!$res) {
                self::dbConn(self::$dbKehu)->insertGetId($ary);
            } else {
                self::dbConn(self::$dbKehu)->where('cname', $ary['cname'])->update($ary);
            }
        }
        return true;
    }

    //定位城市
    public static function toarea()
    {
        $res = self::dbConn(self::$dbKehu)
            ->where('area_id', 0)
            ->orderBy('id', 'desc')
            ->skip(0)->take(100)
            ->get();
        if (!count($res)) return 1;
        foreach ($res as $v) {
            $areaOne = self::dbConn(self::$dbArea)->where('title', 'like', $v->area . '%')->first();
            if (!$areaOne) return 0;
            self::dbConn(self::$dbKehu)->where('id', $v->id)->update(['area_id' => $areaOne->id]);
        }
        return 1;
    }
}